package com.tcl.logoidentify.commons;

public class CompareAlgorithm {
	public static final int FINGERPRINT_LENGTH = 11;
	public static final int CLIENT_CODE_LENGTH = 2 * FINGERPRINT_LENGTH + 2 + 8;
	public static final int SERVER_CODE_LENGTH = FINGERPRINT_LENGTH + 1 + 2 + 2 + 4 + 8;
	/**
	 * 这里这个阈值用于判断两个视频指纹是否一致，当相同的bit数大于该阈值则认为两个视频指纹相一致
	 */
	private static final int THRESH = 80;
	private static final int MAX_DIFF = FINGERPRINT_LENGTH * 8 - THRESH;
	protected static final int[] BITNUM = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3,
			4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4,
			5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };

	public static boolean compare(byte[] clientCode, byte[] serverCode) {
		int sum_4_3 = 0, diff_4_3 = 0, sum_16_9 = 0, diff_16_9 = 0;
		for (int i = 0; i < FINGERPRINT_LENGTH; i++) {
			if (diff_4_3 <= MAX_DIFF || diff_16_9 <= MAX_DIFF) {
				int same_4_3 = BITNUM[(~(clientCode[i] ^ serverCode[i])) & 0xFF];
				int same_16_9 = BITNUM[(~(clientCode[i + FINGERPRINT_LENGTH] ^ serverCode[i])) & 0xFF];
				sum_4_3 += same_4_3;
				sum_16_9 += same_16_9;
				diff_4_3 += 8 - same_4_3;
				diff_16_9 += 8 - same_16_9;
			} else
				return false;
		}

		return sum_4_3 >= THRESH || sum_16_9 >= THRESH;
	}

}
